<template>
  <ElDrawer v-model="opened" :title="formType" size="60%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <el-row>
        <el-col :span="17">
          <el-row>
            <el-col :span="12">
              <ElFormItem label="中文名" :label-width="labelWidth" prop="chName">
                <ElInput v-model="form.chName" />
              </ElFormItem>
            </el-col>
            <el-col :span="12">
              <ElFormItem label="中文拼音" :label-width="labelWidth" prop="chPinyin">
                <ElInput v-model="form.chPinyin" />
              </ElFormItem>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <ElFormItem label="学名" :label-width="labelWidth" prop="scientificName">
                <ElInput v-model="form.scientificName" />
              </ElFormItem>
            </el-col>
            <el-col :span="12">
              <ElFormItem label="物种分类" :label-width="labelWidth" prop="typeLevel">
                <el-tree-select
                  v-model="form.typeLevel"
                  placeholder="选择物种分类"
                  :data="parentOptions"
                  filterable
                  check-strictly
                  :disabled="isView"
                  :render-after-expand="false" />
              </ElFormItem>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <ElFormItem label="国家保护等级" :label-width="labelWidth" prop="protectionLevel">
                <!-- <ElInput v-model="form.protectionLevel" /> -->
                <ElSelect v-model="form.protectionLevel" :default-first-option="true">
                  <ElOption v-for="item in protectionLevels" :key="item.value" :label="item.label" :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </el-col>
            <el-col :span="12">
              <ElFormItem label="是否旗舰物种" :label-width="labelWidth" prop="isSpecies">
                <!-- <ElInput v-model="form.isSpecies" /> -->
                <ElRadioGroup v-model="form.isSpecies" @change="handleRadioChange">
                  <ElRadio label="0" border>是</ElRadio>
                  <ElRadio label="1" border>否</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <ElFormItem label="CITES" :label-width="labelWidth" prop="cites">
                <!-- <ElInput v-model="form.protectionLevel" /> -->
                <ElSelect v-model="form.cites" :default-first-option="true">
                  <ElOption v-for="item in citesSelectData" :key="item.value" :label="item.label" :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </el-col>
            <el-col :span="12">
              <ElFormItem label="IUCN" :label-width="labelWidth" prop="iucn">
                <ElSelect v-model="form.iucn" :default-first-option="true">
                  <ElOption v-for="item in iucnSelectData" :key="item.value" :label="item.label" :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <ElFormItem label="旗舰物种顺序" :label-width="labelWidth" prop="flagshipSpeciesSeq">
                <!-- <ElInput v-model="form.flagshipSpeciesSeq" /> -->
                <ElSelect v-model="form.flagshipSpeciesSeq" :default-first-option="true" :disabled="SpeciesSeqShow">
                  <ElOption v-for="item in flagshipSpeciesSeqs" :key="item.value" :label="item.label" :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </el-col>
            <el-col :span="12" v-show="fungiIds.indexOf(',' + form.typeLevel + ',') > -1">
              <ElFormItem label="生态学" :label-width="labelWidth" prop="ecology">
                <ElSelect v-model="form.ecology" :default-first-option="true">
                  <ElOption v-for="item in ecologyList" :key="item.value" :label="item.label" :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </el-col>
          </el-row>
          <el-row v-show="fungiIds.indexOf(',' + form.typeLevel + ',') > -1">
            <el-col :span="12">
              <ElFormItem label="珍惜濒危真菌" :label-width="labelWidth" prop="isCherish">
                <ElRadioGroup v-model="form.isCherish">
                  <ElRadio :label="1" border>是</ElRadio>
                  <ElRadio :label="0" border>否</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <ElFormItem label="设为图例" :label-width="labelWidth" prop="legend">
                <ElSelect v-model="form.legend" :default-first-option="true">
                  <ElOption v-for="item in AnimalPlant.legendEnum" :key="item.value" :label="item.label" :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </el-col>
            <el-col :span="12">
              <ElFormItem label="冠名物种" :label-width="labelWidth" prop="sponsorship">
                <ElSelect v-model="form.sponsorship" :default-first-option="true">
                  <ElOption v-for="item in AnimalPlant.legendEnum" :key="item.value" :label="item.label" :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <ElFormItem label="分类级别" :label-width="labelWidth" prop="levelNames">
                <ElInput type="textarea" v-model="form.levelNames" />
              </ElFormItem>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <ElFormItem label="简介" :label-width="labelWidth" prop="remark">
                <ElInput type="textarea" v-model="form.remark" :autosize="{ minRows: 5, maxRows: 5 }" />
              </ElFormItem>
            </el-col>
          </el-row>
          <ElFormItem label="物种头像" :label-width="labelWidth" prop="files">
            <UploadImg v-model:image-url="form.files!" :api="uploadAvatar"></UploadImg>
          </ElFormItem>
          <el-row>
            <el-col>
              <div class="box">
                <el-table :data="tableData" style="width: 88%; margin: 0 auto">
                  <el-table-column label="序号" style="text-align: center" width="80">
                    <template #default="scope">
                      <span>{{ scope.$index + 1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="lat" label="经度" style="text-align: center">
                    <template #default="scope">
                      <el-input v-model="scope.row.lat" size="small"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="lng" label="纬度" style="text-align: center">
                    <template #default="scope">
                      <el-input v-model="scope.row.lng" size="small"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" style="text-align: center" fixed="right">
                    <template #default="scope">
                      <el-button @click="deleteTableData(scope.$index)" link icon="Delete" type="primary"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-icon @click="addTableData" class="icon" size="24" color="#fb7a14"><CirclePlusFilled /></el-icon>
              </div>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6" style="margin-left: 30px">
          <div class="flex-x-between" style="display: flex">
            <el-input v-model="permKeywords" style="width: 200px" clearable placeholder="物种级别名称">
              <template #prefix>
                <i-ep-search />
              </template>
            </el-input>

            <div class="flex-center" style="margin-left: 20px; display: flex">
              <el-button type="primary" style="height: 32px" size="small" plain @click="togglePermTree">
                <i-ep-switch />
                {{ isExpanded ? '收缩' : '展开' }}
              </el-button>
              <el-button type="primary" style="height: 32px; margin-left: 5px" size="small" plain @click="submitLevel">
                确认
              </el-button>
            </div>
          </div>
          <ElTree
            ref="permTreeRef"
            node-key="code"
            v-model="form.code"
            :data="menuPermOptions"
            :show-checkbox="true"
            :filter-node-method="handlePermFilter"
            :default-expand-all="true"
            :default-checked-keys="leafNodeId"
            :check-strictly="true"
            class="mt-5">
            <template #default="{ data }">
              {{ data.levelName }}
            </template>
          </ElTree>
        </el-col>
      </el-row>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed, watch } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance, ElMessage, ElMessageBox } from 'element-plus'
import { AnimalPlant } from '@api/tby/summarize/animalPlant/interface'
import { FormType } from '@/enums'
import { getAnimalPlantDetail, saveOrUpdateAnimalPlant, chNameExist } from '@api/tby/summarize/animalPlant'
// import UploadImgs from '@/components/Upload/Imgs.vue'
import { uiUpload } from '@api/upload'
import type { ElTree, UploadUserFile } from 'element-plus'
import UploadImg from '@/components/Upload/Img.vue'
import { SelectOption } from '@/api/interface'
import { listDictByType } from '@api/uc/dict'
import { optionsSpeciesCategory } from '@api/tby/common/speciesCategory'
import { optionsTypeLevel } from '@api/tby/summarize/typeLevel'
import { TbyTypeLevel } from '@api/tby/summarize/typeLevel/interface'
import { checkDecimalMaxNum } from '@api/tby/common/common'

// import { ElMessage } from 'element-plus'
const fileList = ref<UploadUserFile[]>([])
const labelWidth = 190
const opened = ref(false)
const loading = ref(true)
const SpeciesSeqShow = ref(true)
// const isLLView = ref(false)
// const isLAView = ref(false)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<AnimalPlant.Form>>({})
const protectionLevels = ref<SelectOption[]>([])
const ecologyList = ref<SelectOption[]>([])
const citesSelectData = ref<SelectOption[]>([])
const iucnSelectData = ref<SelectOption[]>([])
const flagshipSpeciesSeqs = ref<SelectOption[]>([])
const parentOptions = ref<OptionType[]>([])
const menuPermOptions = ref<TbyTypeLevel.TreeType[]>([])
const permKeywords = ref('')
const permTreeRef = ref<InstanceType<typeof ElTree>>()
const isExpanded = ref(true)
const leafNodeId = ref<any>([])
const fungiIds = ref<string>('')

onMounted(async () => {
  console.log('进来了')
  // 国家保护等级
  getProtectionLevel()
  // 旗舰物种顺序
  getFlagshipSpeciesSeq()
  getCitesOption()
  getIucnOption()
  await getEcology()
  await getFungiIds()
  // 获取所有的菜单
  const { data } = await optionsTypeLevel('')
  menuPermOptions.value = [{ code: 0, levelName: '顶级分类', levelNames: '', level: 0, parentIds: '', children: data }]
})

const tableData = ref<any>([])

function handleRadioChange(value: any) {
  console.log('当前选中的Radio值：', value)
  if (value == 0) {
    SpeciesSeqShow.value = false
  } else {
    SpeciesSeqShow.value = true
  }
}

// 新增一行
const addTableData = () => {
  let newRow: { lat: string; lng: string } = {
    lat: '',
    lng: ''
  }
  tableData.value.push(newRow)
}
// 删除
const deleteTableData = (index: number) => {
  tableData.value.splice(index, 1)
}

/** 权限筛选 */
watch(permKeywords, async val => {
  //  一点击就应该取消默认的选中
  leafNodeId.value = []
  // 清空原来的选中状态
  permTreeRef.value?.setCheckedKeys([])
  const { data } = await optionsTypeLevel(val)
  menuPermOptions.value = [{ code: 0, levelName: '顶级分类', levelNames: '', level: 0, parentIds: '', children: data }]
})
/** 展开/收缩 菜单权限树  */
function togglePermTree() {
  isExpanded.value = !isExpanded.value
  if (permTreeRef.value) {
    Object.values(permTreeRef.value.store.nodesMap).forEach((node: any) => {
      if (isExpanded.value) {
        node.expand()
      } else {
        node.collapse()
      }
    })
  }
}

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

function handlePermFilter(
  value: string,
  data: {
    [key: string]: any
  }
) {
  if (!value) return true
  return data.key.includes(value)
}

const submitLevel = () => {
  if (permTreeRef.value) {
    const checkedNodes = permTreeRef.value.getCheckedNodes()
    console.log(checkedNodes)
    if (checkedNodes.length > 0) {
      let code = ref<string>('')
      let level = ref<string>('')
      let levelNames = ref<string>('')
      for (let i = 0; i < checkedNodes.length; i++) {
        code.value += checkedNodes[i].code + ','
        level.value += checkedNodes[i].level + ','
        levelNames.value += checkedNodes[i].levelNames + ';'
      }
      form.value.typeLevelIds = code.value.substring(0, code.value.length - 1)
      form.value.typeLevels = level.value
      form.value.levelNames = levelNames.value
    }
  }
}

const validateChName = (rule: any, value: any, callback: any) => {
  chNameExist(value, form.value?.id).then(resp => {
    if (!value) {
      return callback()
    }
    if (resp.data) {
      callback(new Error('物种名称已存在'))
    } else {
      callback()
    }
  })
}

const validateEcology = (rule: any, value: any, callback: any) => {
  let result = true
  if (form.value.typeLevel && fungiIds.value.indexOf(',' + form.value.typeLevel + ',') > -1) {
    // 选择的是大型菌类，需要验证生态学
    if (!value) {
      result = false
    }
  }
  if (result === true) {
    return callback()
  } else {
    return callback('请选择生态学')
  }
}

const rules = reactive<FormRules>({
  chName: [
    { required: true, message: '请输入中文名', trigger: 'blur' },
    { max: 20, message: '中文名最大长度为20', trigger: 'blur' },
    { validator: validateChName, trigger: 'blur' }
  ],
  chPinyin: [
    { required: true, message: '请输入中文拼音', trigger: 'blur' },
    { max: 50, message: '中文拼音最大长度为50', trigger: 'blur' }
  ],
  scientificName: [{ max: 50, message: '学名最大长度为50', trigger: 'blur' }],
  isSpecies: [{ required: true, message: '请选择是否旗舰物种', trigger: 'blur' }],
  typeLevel: [{ required: true, message: '请选择物种分类', trigger: 'blur' }],
  protectionLevel: [{ required: true, message: '请输入国家保护等级', trigger: 'blur' }],
  remark: [{ max: 600, message: '简介最大长度为600', trigger: 'blur' }],
  files: [{ required: true, message: '请上传物种头像', trigger: 'blur' }],
  ecology: [{ validator: validateEcology, trigger: 'blur' }]
})

// 国家保护等级 字典
const getProtectionLevel = () => {
  listDictByType('protection_level').then(resp => {
    const { data } = resp
    protectionLevels.value = data
  })
}

/**获取生态学字典 */
const getEcology = async () => {
  let { data } = await listDictByType('ecology')
  ecologyList.value = data
}

/**获取大型菌类的id */
const getFungiIds = async () => {
  fungiIds.value = ''
  let { data } = await listDictByType('common_param')
  let item = data.find(a => a.label === 'fungi_ids')
  if (item) {
    fungiIds.value = item.value
  }
}

const getCitesOption = () => {
  listDictByType('cites').then(resp => {
    const { data } = resp
    citesSelectData.value = data
  })
}

const getIucnOption = () => {
  listDictByType('iucn').then(resp => {
    const { data } = resp
    iucnSelectData.value = data
  })
}

// 旗舰物种顺序 字典
const getFlagshipSpeciesSeq = () => {
  listDictByType('flagship_species_seq').then(resp => {
    const { data } = resp
    flagshipSpeciesSeqs.value = data
  })
}

// 上传头像
function uploadAvatar(formData: FormData) {
  return uiUpload('files', formData)
}

const open = async (type: FormType, id?: number) => {
  fileList.value = []
  tableData.value = []
  form.value = {}
  formType.value = type
  //  一点击就应该取消默认的选中
  leafNodeId.value = []
  // 清空原来的选中状态
  permTreeRef.value?.setCheckedKeys([])
  const { data } = await optionsSpeciesCategory()
  parentOptions.value = [{ value: 0, label: '顶级分类', children: data }]
  console.log('parentOptions.value', parentOptions.value)
  opened.value = true
  if (isAdd.value) {
    form.value.cites = '0'
    form.value.iucn = '0'
    form.value.isCherish = 0
    loading.value = false
  } else {
    try {
      const { data } = await getAnimalPlantDetail(id!)
      loading.value = false
      form.value = data
      if (data.latitudeLongitude) {
        let arr = ref<any>([])
        arr.value = data.latitudeLongitude.split('@')
        for (let i = 0; i < arr.value.length; i++) {
          let arr1 = ref<any>([])
          arr1.value = arr.value[i].split('&')
          let newRow: { lat: string; lng: string } = {
            lat: arr1.value[0],
            lng: arr1.value[1]
          }
          tableData.value.push(newRow)
        }
      }
      if (data.typeLevelIds) {
        leafNodeId.value = data.typeLevelIds?.split(',')
      }
      if (data.isSpecies == '0') {
        SpeciesSeqShow.value = false
      } else {
        SpeciesSeqShow.value = true
      }
      // if (data.wzSpecies) {
      //   leafNodeId.value = [data.wzSpecies]
      //   // leafNodeId.value = typeof data.wzSpecies === 'string' ? data.wzSpecies : ''
      // } else if (data.wzGenus) {
      //   leafNodeId.value = [data.wzGenus]
      //   // leafNodeId.value = typeof data.wzGenus === 'string' ? data.wzSpecies : ''
      // } else if (data.wzSection) {
      //   leafNodeId.value = [data.wzSection]
      // } else if (data.wzCatalogue) {
      //   leafNodeId.value = [data.wzCatalogue]
      // } else if (data.wzCorrect) {
      //   leafNodeId.value = [data.wzCorrect]
      // } else if (data.wzPhylum) {
      //   leafNodeId.value = [data.wzPhylum]
      // } else if (data.wzBoundary) {
      //   leafNodeId.value = [data.wzBoundary]
      // }
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
  form.value = {}
}

const validateLng = (value: string, index: number) => {
  const regExp = /^-?\d+(\.\d+)?$/
  if (value != '' && !regExp.test(value)) {
    ElMessageBox.alert(`第${index}行请输入正确的经度`, '错误描述', {
      confirmButtonText: '确定',
      type: 'error'
    })
    return false
  } else {
    if (!checkDecimalMaxNum(value + '', 7)) {
      ElMessageBox.alert(`第${index}行经度小数点后最多七位小数`, '错误描述', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return false
    }
    let longitude = parseFloat(value)
    if (longitude > 180 || longitude < -180) {
      ElMessageBox.alert(`第${index}行经度范围在 -180 到 180 之间`, '错误描述', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return false
    } else {
      return true
    }
  }
}

const validateLat = (value: string, index: number) => {
  const regExp = /^-?\d+(\.\d+)?$/
  if (value != '' && !regExp.test(value)) {
    ElMessageBox.alert(`第${index}行请输入正确的纬度`, '错误描述', {
      confirmButtonText: '确定',
      type: 'error'
    })
    return false
  } else {
    if (!checkDecimalMaxNum(value + '', 7)) {
      ElMessageBox.alert(`第${index}行纬度小数点后最多七位小数`, '错误描述', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return false
    }
    let latitude = parseFloat(value)
    if (latitude > 90 || latitude < -90) {
      ElMessageBox.alert(`第${index}行纬度范围在 -90 到 90 之间`, '错误描述', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return false
    } else {
      return true
    }
  }
}

const onSaveClicked = () => {
  if (!formRef.value) return
  // form.value.attach = array.join(',')
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const formData = { ...unref(form) }
    if (formData.files == undefined || formData.files == '') {
      ElMessageBox.alert(`请上传物种头像`, '错误描述', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return
    }
    if (tableData.value.length > 0) {
      let latitudeLongitude = ref<string>('')
      for (let i = 0; i < tableData.value.length; i++) {
        let index: number = i + 1
        if (!validateLng(tableData.value[i].lat, index)) {
          return
        }
        if (!validateLat(tableData.value[i].lng, index)) {
          return
        }
        tableData.value[i].lat
        tableData.value[i].lng
        latitudeLongitude.value += tableData.value[i].lat + '&' + tableData.value[i].lng + '@'
      }
      formData.latitudeLongitude = latitudeLongitude.value?.substring(0, latitudeLongitude.value.length - 1)
    } else {
      ElMessageBox.alert(`请维护经纬度`, '错误描述', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return
    }

    saveOrUpdateAnimalPlant(formData).then(response => {
      if (response.code == 0) {
        console.log(response)
        sendSuccess()
        close()
      } else {
        ElMessage({
          type: 'error',
          message: `失败! response.msg`
        })
      }
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
<style lang="scss" scoped>
.box {
  position: relative;
  margin-left: 30px;
  .icon {
    position: absolute;
    bottom: 10px;
    right: 12px;
  }
}
</style>
